<?
class ItemController extends Zend_Controller_Action
{
    protected $session;

    public function preDispatch()
    {
        $this->session = new Zend_Session_Namespace('Default');

        if (!$this->session->items)
        {
            /*
             * Video zc9-introducing-zend-form-part1-screen.mov
             * Then video zc10-introducing-zend-form-part2-screen.mov comment thouse line
            $item1 = new App_ItemDto('item 1','Hello Wold',1);
            $item2 = new App_ItemDto('item 2','Hello Wold',2);

            $this->session->items = array($item1,$item2,$item3);
             *
             */
            $this->session->items = array();
        }
        $this->currentItemId = count($this->session->items);
    }

    public function indexAction()
    {
        

        $this->view->item =$this->session->items;

    }

    public function insertAction()
    {
        $this->view->form = new App_forms_ItemEditor($this->currentItemId,$this->session);

        if($this->getRequest()->isPost())
        {
            if ($this->postBack())
                $this->_helper->Redirector->gotoUrl('/item');
            else
                $this->view->errorElement = $this->view->form->getMessages();
        }

    }

    public function editAction()
    {
        $this->view->form = new App_forms_ItemEditor($this->getRequest()->getParam('id'),$this->session,'edit');
        $this->view->id = $this->getRequest()->getParam('id');
        if($this->getRequest()->isPost())
        {
            if ($this->postBack())
                $this->_helper->Redirector->gotoUrl('/item');
            else
                $this->view->errorElement = $this->view->form->getMessages();
        }
    }

    public function deleteAction()
    {
        if(array_key_exists($this->getRequest()->getParam('id'), $this->session->items))
        {
            $this->session->items[$this->getRequest()->getParam('id')] = null;
            $this->view->message = 'Item Deleted';
        }
        else
        {
            $this->view->message = 'Item not found!';
        }
    }

    /**
     * @return bool
     */
    private function postBack()
    {
        if($this->view->form->isValid($this->getRequest()->getParams()))
        {
            $this->session->items[$this->view->form->getValue('id')] = $this->view->form->MappFormToItemDto();
            return true;
        }
        return false;
    }
}
